import React from 'react';
import {connect} from 'dva/index';
import {Button, Form, message, Modal, Tabs} from 'antd';
import DeliveryReceiptInfo from './deliveryReceiptInfo';
import {fileUpload} from '../../utils/commons';
import Constants from '../../utils/Constants';

const dateFormat = 'YYYY-MM-DD';
const FormItem = Form.Item;
const TabPane = Tabs.TabPane;
const R = require("ramda");

const deliveryReceiptDetail = Form.create()(class DeliveryReceiptDetail extends React.Component {
    constructor(props) {
        super(props);
        this.state = {
            open: false,
            disabled: false,
            accept: false,          //accept为true时，显示市场接单审核模块
            orderType: null,
            cstEdit: null,          //cstEdit为true时,客户信息模块disabled按props里的传递;为false时，通过cstInfoDisabled再判断disabled
            cstInfoDisabled: null,
            isBooking: null,           //isBooking为true时,交接单部分信息从订舱单数据提取
            quickBookingId: null,      //订舱单id
            returnEdit: undefined,      //判断是否为市场退回后修改交接单
            marketUpdate: false,         //是否已转订单之后的市场修改 
            quoOrderDisabled: undefined,     //线上下单客户模块disable判断
            channel: undefined, // 
        }
    }

    handleOpen = (disabled, accept, orderType, cstEdit, cstInfoDisabled, isBooking, quickBookingId, returnEdit, marketUpdate, quoOrderDisabled , channel) => {
        this.setState({ open: true, disabled, accept, orderType, cstEdit, cstInfoDisabled, isBooking, quickBookingId, returnEdit, marketUpdate, quoOrderDisabled,channel });
    }

    handleCancel = () => {
        this.setState({ open: false });
        this.props.form.resetFields();
        this.props.deliveryReceipt.deliveryReceipt = {}
        this.props.deliveryReceipt.company = {}
    }

    closeWin = () => {
        this.handleCancel();
        if (this.props.refreshList) this.props.refreshList();
    }

    handleApproval = () =>{
        let form = this.deliveryReceiptInfo.checkDeliveryReceiptInfo() ? this.deliveryReceiptInfo.checkDeliveryReceiptInfo() : null;
        let drData = this.props.deliveryReceipt.deliveryReceipt ? this.props.deliveryReceipt.deliveryReceipt : null;
        form.id = drData && drData.id ? drData.id : null;
        form.orderId = drData && drData.orderId ? drData.orderId : null;
        form.isNeedSo = form.approvalresult == "3" && (drData.shipping || drData.airFreight) ? '1' : '0';
        form.status = form.approvalresult


        if(form.isNeedSo == '1'){
            if(form.approvalresult == "3"){
                form.soUrl = this.deliveryReceiptInfo.refs.soUrl.getUrl();
                if (!(this.deliveryReceiptInfo.refs.soUrl.getFiles().length > 0) || R.isNil(form.soNo)){
                    form.status = "5";
                }
            }
        }
        this.props.dispatch({
            type: this.state.marketUpdate ? 'deliveryReceipt/updateDeliveryReceipt' : 'deliveryReceipt/ApprovalDeliveryReceipt',
            payload: {
                ...form,
                onSuccess: (id) => {
                    let flag = this.deliveryReceiptInfo && this.deliveryReceiptInfo.refs && this.deliveryReceiptInfo.refs.soUrl;
                    if (flag && form.status === "3" && !this.deliveryReceiptInfo.refs.soUrl.getUrl() && this.deliveryReceiptInfo.refs.soUrl.getFiles().length > 0) {     //此判断的意思是，附件更换过，从无到有或者从A到B
                        fileUpload({
                            id,
                            modules: Constants.BOOKING_MODULES[0],
                            data: this.deliveryReceiptInfo.refs.soUrl.getFiles(),
                            onSuccess: this.closeWin,
                            onFail: this.closeWin
                        });
                    } else {
                        this.closeWin()
                    }
                    this.closeWin()
                }
            }
        })
    }

    handleConfirm = (status) => {
        let form = this.deliveryReceiptInfo.checkDeliveryReceiptInfo() ? this.deliveryReceiptInfo.checkDeliveryReceiptInfo() : null;
        if (R.isNil(form.cstId) && R.isNil(form.companyName) && this.props.quickBooking.dataSource.cstName ) {        
            message.error("客户未保存或未选择客户");
            return;
        }
        if(!(form.shipping || form.airFreight || form.portService || form.vasService)){
            message.error("请至少选择一项服务项目");
            return;
        }
        if(["1", "3"].includes(form.shipping) || ["1", "2"].includes(form.portService)){
            if(!(form.size20gp || form.size40gp || form.size40hq )){
                message.error("请至少输入一种柜型数量");
                return;
            }
        }
        form.id = this.props.deliveryReceipt.deliveryReceipt && this.props.deliveryReceipt.deliveryReceipt.id ? this.props.deliveryReceipt.deliveryReceipt.id : null;
        form.orderType = this.state.orderType
        form.status = status

        form.cstPriceDesc = R.isNil(form.newCstPriceDesc) || R.isEmpty(form.newCstPriceDesc) ? form.cstPriceDesc : form.cstPriceDesc + "\n\n" + form.newCstPriceDesc;
        form.companyPriceDesc = R.isNil(form.newCompanyPriceDesc) || R.isEmpty(form.newCompanyPriceDesc) ? form.companyPriceDesc : form.companyPriceDesc + "\n\n" + form.newCompanyPriceDesc; 

        if (!R.equals(R.pick(Object.keys(form), this.props.deliveryReceipt.dataSource), form)) {
            this.props.dispatch({
                type: R.isNil(form.id) ? 'deliveryReceipt/createDeliveryReceipt' : 'deliveryReceipt/updateDeliveryReceipt',
                payload: {
                    ...form,
                    quickBookingId: this.state.quickBookingId,
                    onSuccess: (id) => {
                        this.closeWin()
                    }
                }
            })
        } else this.handleCancel();
    }

    render() {
        let formItemLayout = { labelCol: { span: 8 }, wrapperCol: { span: 14 } };
        let formItemLayout2 = { labelCol: { span: 4 }, wrapperCol: { span: 18 } };
        const { getFieldDecorator } = this.props.form;
        let footer = [
            <Button key="save" size="large" loading={this.props.loading} onClick={this.handleConfirm.bind(this, "1")} style={{ display: this.state.disabled || this.state.quoOrderDisabled ? 'none' : 'inline-block' }}>保存</Button>,            
            <Button key="saveApproval" size="large" loading={this.props.loading} onClick={this.handleConfirm.bind(this, "2")} style={{ display: this.state.disabled ? 'none' : 'inline-block' }}>保存并提交审核</Button>,
            <Button key="cancel" size="large" loading={this.props.loading} onClick={this.handleCancel.bind(this, true)}>{this.state.disabled ? "关闭" : "取消"}</Button>
        ];

        let footer2 = [
            <Button key="approval" size="large" loading={this.props.loading} style={{ display: this.props.deliveryReceipt.deliveryReceipt.status == "2" ? 'inline-block' : 'none' }} onClick={this.handleApproval.bind(this)}>保存并提交</Button>,
            <Button key="cancel" size="large" loading={this.props.loading} onClick={this.handleCancel.bind(this, true)}>{this.props.deliveryReceipt.deliveryReceipt.status == "2"  ? "取消" : "关闭"}</Button>
        ];

        //市场修改
        let footer3 = [
            <Button key="save" size="large" loading={this.props.loading} style={{ display: ["3", "5"].includes(this.props.deliveryReceipt.deliveryReceipt.status) ? 'inline-block' : 'none' }} onClick={this.handleApproval.bind(this)}>保存</Button>,
            <Button key="cancel" size="large" loading={this.props.loading} onClick={this.handleCancel.bind(this, true)}>{this.props.deliveryReceipt.deliveryReceipt.status == "3"  ? "取消" : "关闭"}</Button>
        ];

        let dataSource = this.props.deliveryReceipt.deliveryReceipt ? this.props.deliveryReceipt.deliveryReceipt : {};
        let title = <span>交接单详情</span>;
        if (dataSource.status === "4") {
            title = <span style={{ color: 'red' }}>交接单详情(市场退回原因: {dataSource.approvalMemo})</span>
        }

        return (
            <div>
                {this.state.open ?
                    <Modal  maskClosable={false}
                            visible={this.state.open}
                            width={930} title={title}
                            confirmLoading={this.props.loading}
                            onCancel={this.handleCancel.bind(this)}
                            footer={this.state.accept && !this.state.marketUpdate ? footer2 :  this.state.marketUpdate ? footer3 : footer}>
                        <DeliveryReceiptInfo
                            wrappedComponentRef={(inst) => this.deliveryReceiptInfo = inst}
                            disabled={this.state.disabled}
                            accept={this.state.accept}
                            cstEdit={this.state.cstEdit}
                            cstInfoDisabled={this.state.cstInfoDisabled}
                            isBooking={this.state.isBooking}
                            returnEdit={this.state.returnEdit}
                            marketUpdate={this.state.marketUpdate}
                            quoOrderDisabled={this.state.quoOrderDisabled}
                            channel={this.state.channel}
                            />
                    </Modal>
                : null}
            </div>
        )
    }
})

function mapStateToProps(state) {
    return {
        loading: state.loading.models.deliveryReceipt, deliveryReceipt: state.deliveryReceipt, quickBooking: state.quickBooking
    };
}

export default connect(mapStateToProps)(deliveryReceiptDetail);